package cn.getway.config;

import cn.getway.config.web.ResponseMessage;
import cn.getway.config.web.ResponseStatusCode;
import cn.getway.utils.GsonTool;
import com.netflix.client.ClientException;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 毛苏宇
 * User: me
 * Date: 2020/6/21
 * Time: 18:59
 * Description:
 */
@Configuration
public class FallBackConfig implements FallbackProvider {


    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(final String route, final Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                //异常代码
                return HttpStatus.BAD_REQUEST.value();
            }

            @Override
            public String getStatusText() throws IOException {
                //返回异常的简单描述
                return HttpStatus.BAD_REQUEST.getReasonPhrase();
            }

            @Override
            public void close() {}

            @Override
            public InputStream getBody() throws IOException {
                if (cause instanceof ClientException){
                    return new ByteArrayInputStream(GsonTool.objectToJson(new ResponseMessage(ResponseStatusCode.CODE_SYSTEM_ERROR, "服务暂不可用",null)).getBytes());
                }
                return new ByteArrayInputStream(GsonTool.objectToJson(new ResponseMessage(ResponseStatusCode.CODE_SYSTEM_ERROR, "操作发生错误",null)).getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
                httpHeaders.setDate(System.currentTimeMillis());
                httpHeaders.setConnection("keepalive");
                httpHeaders.setCacheControl(CacheControl.noCache());
                return httpHeaders;
            }
        };
    }


}
